package com.example.design.a.singleton;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 假装这是一个连接池
 */
public class ConnectionPool {

    private final List<MyConnection> POOL;

    /**
     * 构造方法
     * 实例化连接池对象
     */
    public ConnectionPool() {
        this(10);
    }

    public ConnectionPool(int capital) {
        this.POOL = new ArrayList<>();
        if (capital == 0) {
            capital = 10;
        }
        for (int i = 0; i < capital; i++) {
            this.add(MyConnection.getConnection());
        }
    }

    /**
     * 添加一个连接
     *
     * @param connection
     */
    public void add(MyConnection connection) {
        if (connection != null) {
            POOL.add(connection);
        }
    }

    /**
     * 获取一个随机连接
     *
     * @return
     */
    public MyConnection getConnection() {
        Random r = new Random();
        int len = this.POOL.size();
        int index = r.nextInt(len);
        return this.POOL.get(index);
    }

}
